package com.gw.vip.message.zib;

import com.gw.vip.common.exception.ExceptionEnums;
import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.message.dto.MessageDto;
import com.gw.vip.message.po.UserTemplateInfo;
import com.gw.vip.message.service.UserTemplateInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author GW
 * @description
 * @since 2022-04-17
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class MessageBiz {

    @Value("${spring.mail.username}")
    private String from;

    private final UserTemplateInfoService userTemplateInfoService;
    private final JavaMailSender mailSender;

    public void send(MessageDto dto) {
        UserTemplateInfo userTemplateInfo = userTemplateInfoService.getById(dto.getTemplateId());
        if (userTemplateInfo==null){
            log.error("消息模板不存在！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "消息模板不存在！");
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(dto.getTos());
        message.setSubject(userTemplateInfo.getSubject());

        String text = userTemplateInfo.getMessage();
        Map<String, String> params = dto.getParams();
        if (dto.getParams()==null){
            params = new HashMap<>(0);
        }
        text = this.parse(text, params);
        message.setText(text);
        log.info("邮件内容:{}", text);
        try {
            mailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
            throw new ServiceException("邮件发送失败！");
        }
    }

    //--------------------------------------------- 辅助函数 ----------------------------------------------//

    private String parse(String content, Map<String, String> kvs) {
        String pattern = "\\$\\{(.*?)}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);
        StringBuffer sr = new StringBuffer();
        while (m.find()) {
            String group = m.group().substring(2, m.group().length()-1);
            m.appendReplacement(sr, kvs.get(group));
        }
        m.appendTail(sr);
        return sr.toString();
    }

}
